package com.citi.xylophone.phoneEmulator.audio;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import org.apache.commons.io.FileUtils;

import com.citi.xylophone.phoneEmulator.global.GlobalSwap;
import com.citi.xylophone.phoneEmulator.model.SourceAudio;
import com.citi.xylophone.phoneEmulator.view.MainPanelview;

public class AudioThread extends Thread  {

	private List<SourceAudio> listSourceAudio = new ArrayList<SourceAudio>();
	private boolean active;
	private MainPanelview mainPanelview;

	
	public void setMainPanelview(MainPanelview mainPanelview) {
		this.mainPanelview = mainPanelview;
	}


	public void stopAudioThread() throws InterruptedException{
		active = false;
	}


	public AudioThread(List<SourceAudio> listSourceAudio) {

		active = true;
		this.listSourceAudio = listSourceAudio;
		
	}
	
	

	public void run() {
		
		
		for (SourceAudio sourceAudio:listSourceAudio){
			
			if (!active){
				return;
			}
			playAudio(sourceAudio);			
		}
		
		try {
			sendEventFinishAudio();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void sendEventFinishAudio() throws Exception {
		
		mainPanelview.eventFinishAudios();
		
	}


	private void playAudio(SourceAudio sourceAudio) {

		try {
			
			Clip sonido = AudioSystem.getClip();
			
			String  urlAudio = sourceAudio.getUrlAudio();
			
			if (GlobalSwap.getAudioIP()!=null){
				 urlAudio = urlAudio.replace("localhost", GlobalSwap.getAudioIP());
			}
			
			URL url = new URL(urlAudio);
			
			File file = File.createTempFile("tempWav", ".wav");
			file.deleteOnExit();
			FileUtils.copyURLToFile(url, file);
			sonido.open(AudioSystem.getAudioInputStream(file));

			sonido.start();			
			Thread.sleep(500);
			while (sonido.isRunning()) {
				Thread.sleep(500);
				
				if (!active){
					sonido.stop();
					break;
				}
			}
			sonido.close();

		} catch (Exception e) {
			System.out.println("Error in " + sourceAudio.getUrlAudio());
			e.printStackTrace();
		}
	}

}
